﻿using ALEXBlog.Entity;
using ALEXBlog.Entity.ViewModel;
using ALEXBlog.IService;
using ALEXBlog.IService.Redis;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace ALEXBlog.Controller
{
    [Route("api/[controller]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        //使用Util注入
        //IUsersService usersContext = AutofacHelper.AutofacUtil.GetScopeService<IUsersService>();
        IUsersService usersContext;
        IMapper mapperContext;
        IRedisService redisContext;

        public UsersController(IMapper mapper, IUsersService usersService, IRedisService redisService)
        {
            mapperContext = mapper;
            usersContext = usersService;
            redisContext = redisService;
        }

        //[HttpGet]
        //[Authorize(Roles = nameof(Role.Users))]
        //public Task<IActionResult> GetUsers()
        //{
        //    return Ok();
        //}

        [HttpGet("{userId}", Name = nameof(GetUser))]
        //[Authorize(Roles = nameof(Role.Users))]
        public async Task<IActionResult> GetUser(string userId)
        {
            if (userId == string.Empty || userId == null)
            {
                return BadRequest();
            }
            var user = await usersContext.QueryAsync(d => d.Id.ToString() == userId);
            return user is not null ? Ok(user) : NotFound();
        }

        [HttpPost]
        //[Authorize(Roles = nameof(Role.Admin))]
        public async Task<IActionResult> AddUsers(UsersModel model)
        {
            if (model is null)
            {
                return BadRequest();
            }
            if (await usersContext.AddAsync(model) > 0)
            {
                return CreatedAtRoute(nameof(GetUser), new { userId = model.Id.ToString() }, model);
            }

            //Redis测试代码
            //if (await redisContext.SetAsync("testKey", model, TimeSpan.FromMinutes(3)))
            //{
            //    return CreatedAtRoute(nameof(GetUser), new { userId = model.Id.ToString() }, await redisContext.GetAsync("testKey"));
            //}

            return BadRequest();
        }

        [HttpDelete]
        //[Authorize(Roles = nameof(Role.Admin))]
        public async Task<IActionResult> RemoveUsers(string userId)
        {
            if (userId == string.Empty || userId == null)
            {
                return BadRequest();
            }
            return await usersContext.RemoveAsync(userId) > 0 ? NoContent() : NotFound();
        }

        [HttpPut]
        //[Authorize(Roles = nameof(Role.Users))]
        public async Task<IActionResult> UpdateUsers(UsersVM userVM)
        {
            if (userVM is null)
            {
                return BadRequest();
            }
            return await usersContext.UpdateAsync(userVM) > 0 ? NoContent() : BadRequest();
        }

    }
}
